import uuid

import requests
from alibabacloud_cloudauth20190307 import models as cloudauth_models
from alibabacloud_cloudauth20190307.client import Client as CloudauthClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

import settings
from social.exceptions import CodeException


class InitFaceVerify:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
            endpoint: str,
    ) -> CloudauthClient:
        config = open_api_models.Config(
            # 您的AccessKey ID。
            access_key_id=settings.OSS_ACCESS_KEY_ID,
            # 您的AccessKey Secret。
            access_key_secret=settings.OSS_ACCESS_KEY_SECRET,
            endpoint=endpoint
        )
        return CloudauthClient(config)

    @staticmethod
    def request_cert_id(user_id, order_no, meta_info, cert_name: str = None, cert_no: str = None,
                        product_code: str = 'LR_FR'):
        request = cloudauth_models.InitFaceVerifyRequest(
            # 请输入场景ID。
            scene_id=1000008036,
            outer_order_no=order_no,
            # 要接入的认证方案。
            product_code=product_code,
            model='MULTI_ACTION',
            # 固定值IDENTITY_CARD。
            cert_type='IDENTITY_CARD',
            meta_info=meta_info,
            user_id=user_id,
            cert_name=cert_name,
            cert_no=cert_no

        )
        response = InitFaceVerify.init_face_verify_auto_route(request)
        print(response)
        if response.body.code != '200':
            raise CodeException(msg=response.body.message)
        return response.body.result_object.certify_id

    @staticmethod
    def init_face_verify_auto_route(
            request: cloudauth_models.InitFaceVerifyRequest,
    ) -> cloudauth_models.InitFaceVerifyResponse:
        endpoints = [
            'cloudauth.cn-shanghai.aliyuncs.com',
            'cloudauth.cn-beijing.aliyuncs.com'
        ]
        for endpoint in endpoints:
            try:
                response = InitFaceVerify.init_face_verify(endpoint, request)
                if UtilClient.equal_number(500, response.status_code):
                    continue
                if response is not None and response.body is not None:
                    if UtilClient.equal_string("500", response.body.code):
                        continue
                return response
            except Exception as err:
                # 网络异常，切换到下个区域调用。
                continue
        return None

    @staticmethod
    def init_face_verify(
            endpoint: str,
            request: cloudauth_models.InitFaceVerifyRequest,
    ) -> cloudauth_models.InitFaceVerifyResponse:
        client = InitFaceVerify.create_client(endpoint)
        # 创建RuntimeObject实例并设置运行参数。
        runtime = util_models.RuntimeOptions()
        runtime.read_timeout = 10000
        runtime.connect_timeout = 10000
        return client.init_face_verify_with_options(request, runtime)


class DescribeFaceVerify:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
            endpoint: str,
    ) -> CloudauthClient:
        config = open_api_models.Config(
            # 您的AccessKey ID。
            access_key_id=settings.OSS_ACCESS_KEY_ID,
            # 您的AccessKey Secret。
            access_key_secret=settings.OSS_ACCESS_KEY_SECRET,
            endpoint=endpoint,
        )
        return CloudauthClient(config)

    @staticmethod
    def request_describe_face_verify(cert_id):
        request = cloudauth_models.DescribeFaceVerifyRequest(
            # 请输入场景ID。
            scene_id=1000008036,
            certify_id=cert_id
        )
        res = DescribeFaceVerify.describe_face_verify_auto_route(request)
        if res.body.code != '200':
            raise CodeException(msg=res.body.message)
        return res

    @staticmethod
    def describe_face_verify_auto_route(
            request: cloudauth_models.DescribeFaceVerifyRequest,
    ) -> cloudauth_models.DescribeFaceVerifyResponse:
        endpoints = [
            'cloudauth.cn-shanghai.aliyuncs.com',
            'cloudauth.cn-beijing.aliyuncs.com'
        ]
        for endpoint in endpoints:
            try:
                response = DescribeFaceVerify.describe_face_verify(endpoint, request)
                if UtilClient.equal_number(500, response.status_code):
                    continue
                if response is not None and response.body is not None:
                    if UtilClient.equal_string("500", response.body.code):
                        continue
                return response
            except Exception as err:
                print(err)
                continue
        return None

    @staticmethod
    def describe_face_verify(
            endpoint: str,
            request: cloudauth_models.DescribeFaceVerifyRequest,
    ) -> cloudauth_models.DescribeFaceVerifyResponse:
        client = DescribeFaceVerify.create_client(endpoint)
        # 创建RuntimeObject实例并设置运行参数。
        runtime = util_models.RuntimeOptions()
        runtime.read_timeout = 10000
        runtime.connect_timeout = 10000
        return client.describe_face_verify_with_options(request, runtime)


class LivenessFaceVerify:

    @staticmethod
    def check_face(face_url):
        header = {
            'Authorization': 'APPCODE fb22ecc9f2444bb4946f10e0fd182683'
        }
        data = {
            'url': face_url
        }
        r = requests.post(url='http://liveck.market.alicloudapi.com/lundear/liveck', headers=header, data=data)
        return r.json()


class CompareFaceVerify:
    @staticmethod
    def create_client(
            endpoint: str,
    ) -> CloudauthClient:
        config = open_api_models.Config(
            access_key_id=settings.OSS_ACCESS_KEY_ID,
            access_key_secret=settings.OSS_ACCESS_KEY_SECRET,
            endpoint=endpoint
        )
        return CloudauthClient(config)

    @staticmethod
    def compare(source_url, target_url):
        request = cloudauth_models.CompareFaceVerifyRequest(
            # 请输入场景ID。
            scene_id=1000008036,
            outer_order_no=str(uuid.uuid4()),
            product_code='PV_FC',
            source_face_contrast_picture_url=source_url,
            target_face_contrast_picture_url=target_url,
        )
        response = CompareFaceVerify.compare_face_verify_auto_route(request)
        return response

    @staticmethod
    def compare_face_verify_auto_route(
            request: cloudauth_models.CompareFaceVerifyRequest,
    ) -> cloudauth_models.CompareFaceVerifyResponse:
        endpoints = [
            'cloudauth.cn-shanghai.aliyuncs.com',
            'cloudauth.cn-beijing.aliyuncs.com'
        ]
        for endpoint in endpoints:
            try:
                response = CompareFaceVerify.compare_face_verify(endpoint, request)
                if UtilClient.equal_number(500, response.status_code):
                    continue
                if response is not None and response.body is not None:
                    if UtilClient.equal_string("500", response.body.code):
                        continue
                return response
            except Exception as err:
                continue
        return None

    @staticmethod
    def compare_face_verify(
            endpoint: str,
            request: cloudauth_models.CompareFaceVerifyRequest,
    ) -> cloudauth_models.CompareFaceVerifyResponse:
        client = CompareFaceVerify.create_client(endpoint)
        # 创建RuntimeObject实例并设置运行参数。
        runtime = util_models.RuntimeOptions()
        runtime.read_timeout = 10000
        runtime.connect_timeout = 10000
        return client.compare_face_verify_with_options(request, runtime)
